updating = false;

oEditors = [];

(function($)
{
	$(document).ready(function()
	{
		foundationTable = $('#foundationTable').dataTable(
		{
			bRetrieve : true,
			bProcessing : false,
			bServerSide : true,
			bFilter : false,
			bInfo : true,
			bLengthChange : false,
			bSort : true,
			sAjaxDataProp: 'foundations',
			sServerMethod: 'POST',
			sPaginationType: 'full_numbers',
			sAjaxSource : '{0}/foundation/list'.format(contextPath),
			fnServerParams : function(aoData)
			{
				aoData.push(
				{
					name : "foundationName",
					value : $('input[name="searchFoundationName"]').val(),
				},
				{
					name : "address",
					value : $('input[name="searchAddress"]').val(),
				},
				{
					name : "operatingMethod",
					value : $('input[name="searchOperatingMethod"]').val(),
				},
				{
					name : "searchLeaseDeposit",
					value : $('select[name="searchLeaseDeposit"]').val(),
				},
				{
					name : "searchFacilitiesInvestment",
					value : $('select[name="searchFacilitiesInvestment"]').val(),
				},
				{
					name : "searchPremium",
					value : $('select[name="searchPremium"]').val(),
				},
				{
					name : "searchUnionFee",
					value : $('select[name="searchUnionFee"]').val(),
				},
				{
					name : "searchSupportFund",
					value : $('select[name="searchSupportFund"]').val(),
				},
				{
					name : "searchTotalFee",
					value : $('select[name="searchTotalFee"]').val(),
				},
				{
					name : "searchMonthlyRentalFee",
					value : $('select[name="searchMonthlyRentalFee"]').val(),
				},
				{
					name : "searchCommision",
					value : $('select[name="searchCommision"]').val(),
				},
				{
					name : "searchServiceCharge",
					value : $('select[name="searchServiceCharge"]').val(),
				},
				{
					name : "searchSalesPerDay",
					value : $('select[name="searchSalesPerDay"]').val(),
				},
				{
					name : "searchSalesPerMonth",
					value : $('select[name="searchSalesPerMonth"]').val(),
				});
			},
			aoColumns :
			[
				{
					sTitle : '업종',
					mDataProp : 'businessType',
					bSortable : true,
					asSorting : [ 'asc', 'desc' ],
					sClass : 'center'
				},
				{
					sTitle : '명칭',
					mDataProp : 'foundationName',
					bSortable : true,
					asSorting : [ 'asc', 'desc' ],
					sClass : 'nosort',
					sDefaultContent: '-'
				},
				{
					sTitle : '평수',
					mDataProp : 'pyung',
					bSortable : true,
					sDefaultContent: '-',
				},
				{
					sTitle : '해당층',
					mDataProp : 'floor',
					bSortable : true,
					sDefaultContent: '-',
				},
				{
					sTitle : '계약 형태',
					mDataProp : 'contractType',
					bSortable : true,
					sDefaultContent: '-',
				},
				{
					sTitle : '임대 기간',
					mDataProp : 'leasePeriod',
					bSortable : true,
					sDefaultContent: '-',
				},
				{
					sTitle : '개업 시기',
					mDataProp : 'foundingTime',
					bSortable : true,
					sDefaultContent: '-',
				},
				{
					sTitle : '매매 사유',
					mDataProp : 'dealingCause',
					bSortable : true,
					sDefaultContent: '-',
				}
			],
			fnInfoCallback : function(oSettings, iStart, iEnd, iMax, iTotal, sPre)
			{
				return "전체 " + iMax + "건 중 " + iStart + "부터 " + (iMax < iEnd ? iMax : iEnd) + "까지";
			}
		});
		
		$('#foundationTable tbody').unbind('click').delegate('tr', 'click', function(event)
		{
			var foundation = foundationTable.fnGetData(this);
			
			$('input[name="selectedId"]').val(foundation.foundationId);
			
			showFoundationEditPopup(event);
		});
		
		$('form[name="searchForm"] select').change(function(event) { foundationTable.fnDraw(); });
		
		$('#searchButton').unbind('click').click(function(event){ foundationTable.fnDraw(); });
		
		$('#registerButton').unbind('click').click(showFoundationEditPopup);
		$('#resetButton').unbind('click').click(resetEditForm);
	});
	
	/**
	 * 매장 편집 팝업을 개방한다.
	 */
	function showFoundationEditPopup(event)
	{
		var popupContents = '<div class="maincontent">' +
				'<div class="contentinner content-editprofile">' +
				'<h4 class="widgettitle nomargin">매장 편집</h4>' +
				'<div class="widgetcontent bordered" style="overflow: auto; height: 740px;">' +
					'<form id="foundationEditForm" action="{0}/foundation/save" class="editprofileform" method="post">' +
						'<input type="hidden" name="foundationId" value="0" />' +
						'<div class="row-fluid">' +
							'<div class="span8">' +
								'<p>' +
									'<label>업종</label>' +
									'<span class="field"><input type="text" name="businessType" class="input-medium" /></span>' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<p>' +
									'<label>명칭</label>' +
									'<span class="field"><input type="text" name="foundationName" class="input-medium" /></span>' +
								'</p>' +
							'</div>' +
						'</div>' +
						'<div class="row-fluid">' +
							'<div class="span8">' +
								'<p>' +
									'<label>위치</label>' +
									'<span class="field"><input type="text" name="location" class="input-medium" /></span>' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<p>' +
									'<label>특징</label>' +
									'<span class="field"><input type="text" name="feature" class="input-medium" /></span>' +
								'</p>' +
							'</div>' +
						'</div>' +
						'<div class="row-fluid">' +
							'<div>' +
								'<p>' +
									'<label>주소</label>' +
									'<span class="field"><input type="text" name="address" style="width: 807px;" /></span>' +
								'</p>' +
							'</div>' +
						'</div>' +	
						'<div class="row-fluid">' +
							'<div class="span4">' +
								'<h4>물건 규모/임대차 현황</h4>' +
								'<p>' +
									'<label>평수</label>' +
									'<input type="text" name="pyung" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>총층수</label>' +
									'<input type="text" name="grossFloor" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>해당층</label>' +
									'<input type="text" name="floor" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>계약 형태</label>' +
									'<input type="text" name="contractType" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>임대 기간</label>' +
									'<input type="text" name="leasePeriod" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>개업 시기</label>' +
									'<input type="text" name="foundingTime" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>매매 사유</label>' +
									'<input type="text" name="dealingCause" class="input-medium" value="" />' +
								'</p>' +
								'<h4>물건 현황</h4>' +
								'<p>' +
									'<label>일매출</label>' +
									'<input type="text" name="salesPerDay" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>월매출</label>' +
									'<input type="text" name="salesPerMonth" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>종업원수</label>' +
									'<input type="text" name="employeeNumber" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>인건비</label>' +
									'<input type="text" name="personnelExpenses" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>재료비</label>' +
									'<input type="text" name="materialCost" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>월순익</label>' +
									'<input type="text" name="netProfitPerMonth" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>좌석수</label>' +
									'<input type="text" name="seatingCapacity" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>피크 타임</label>' +
									'<input type="text" name="peakTime" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>영업 시간</label>' +
									'<input type="text" name="operatingHour" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>운영 방식</label>' +
									'<input type="text" name="operatingMethod" class="input-medium" value="" />' +
								'</p>' +
							'</div>' +
							'<div class="span4">' +
								'<h4>물건 금액</h4>' +
								'<p>' +
									'<label>임대 보증금</label>' +
									'<input type="text" name="leaseDeposit" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>시설 투자금 / 권리금</label>' +
									'<input type="text" name="facilitiesInvestment" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>가맹비 / 운영지원금</label>' +
									'<input type="text" name="unionFee" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>기타 비용</label>' +
									'<input type="text" name="regionPreference" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>합계</label>' +
									'<input type="text" name="totalFee" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>월세/관리비/수수료/관리비</label>' +
									'<input type="text" name="monthlyRentalFee" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>용역비</label>' +
									'<input type="text" name="serviceCharge" class="input-medium" value="" />' +
								'</p>' +
								'<p>' +
									'<label>비고</label>' +
									'<textarea name="feeReferences" class="span7"></textarea>' +
								'</p>' +
								'<h4>상권 정보</h4>' +
								'<div>' +
		                            '<textarea id="businessDistrictZoneHistory" name="businessDistrictZoneHistory" rows="18" cols="100"></textarea>' +
		                        '</div>' +
							'</div>' +
							'<div class="span4">' +
								'<h4>매출 내역</h4>' +
								'<p>' +
									'<textarea id="salesHistory" name="salesHistory" rows="17" cols="100"></textarea>' +
								'</p>' +
								'<h4>기타 정보</h4>' +
								'<p>' +
									'<textarea id="note" name="note" rows="17" cols="100"></textarea>' +
								'</p>' +
							'</div>' +
						'</div>' +
					'</form>' +
					'<div class="divider15"></div>' +
					'<div>' +
						'<button id="resetButton" type="button" class="btn">새 매장</button> ' +
						'<button id="saveButton" type="submit" class="btn btn-primary">저장</button> ' +
						'<button id="reportButton" type="button" class="btn">보고서</button> ' +
					'</div>' +
				'</div><!--widgetcontent-->' +
			'</div><!--contentinner-->' +
		'</div><!--maincontent-->';
		
		popupContents = popupContents.format(contextPath);
		
		$(this).speedoPopup(
		{
			theme : 'default',
			width : 1680,
			height : 820,
			onShow : editPopupShown,
			onComplete : editPopupComplete,
			onClose : editPopupClosed,
			htmlContent : popupContents
		});
	}
	
	/**
	 * 편집 팝업의 구성이 완료된 뒤에 실행된다.(최초에 한번만 실행된다.)
	 */
	function editPopupComplete(event)
	{
		$('#saveButton').unbind('click').click(saveFoundation);
		$('#reportButton').unbind('click').click(showReport);
		
		nhn.husky.EZCreator.createInIFrame(
		{
			oAppRef: oEditors,
			elPlaceHolder: "businessDistrictZoneHistory",
			sSkinURI: "{0}/resources/javascript/smarteditor2/SmartEditor2Skin.html".format(contextPath),
			fCreator: "createSEditor2",
			fOnAppLoad: function()
			{
				oEditors.getById["businessDistrictZoneHistory"].exec('SET_IR', [ $('textarea[name="businessDistrictZoneHistory"]').val() ]);
			}
		});
		
		nhn.husky.EZCreator.createInIFrame(
		{
			oAppRef: oEditors,
			elPlaceHolder: "salesHistory",
			sSkinURI: "{0}/resources/javascript/smarteditor2/SmartEditor2Skin.html".format(contextPath),
			fCreator: "createSEditor2",
			fOnAppLoad: function()
			{
				oEditors.getById["salesHistory"].exec('SET_IR', [ $('textarea[name="salesHistory"]').val() ]);
			}
		});
		
		nhn.husky.EZCreator.createInIFrame(
		{
			oAppRef: oEditors,
			elPlaceHolder: "note",
			sSkinURI: "{0}/resources/javascript/smarteditor2/SmartEditor2Skin.html".format(contextPath),
			fCreator: "createSEditor2",
			fOnAppLoad: function()
			{
				oEditors.getById["note"].exec('SET_IR', [ $('textarea[name="note"]').val() ]);
			}
		});
	}
	
	/**
	 * 편집 팝업이 개방된 뒤에 실행된다.(열때마다 실행된다.)
	 */
	function editPopupShown(event)
	{
		var foundationId = $('input[name="selectedId"]').val();
		
		// 매장을 새로 등록하는 경우 이후 과정은 수행하지 않는다.
		if (!foundationId || foundationId < 1)
		{
			return;
		}
		
		getFoundation(foundationId);
	}
	
	/**
	 * 편집 팝업이 닫힌 뒤에 실행된다.
	 */
	function editPopupClosed(event)
	{
		resetEditForm();
	}
	
	/**
	 * 편집 폼을 초기 상태로 되돌린다. 
	 */
	function resetEditForm(event)
	{
		$("#foundationEditForm").each(function()
		{
			this.reset();
		});
	}
	
	/**
	 * 매장 정보를 편집 폼에 설정한다.
	 */
	function setFoundationToForm(foundation)
	{
		$('input[name="foundationId"]').val(foundation.foundationId);
		$('input[name="businessType"]').val(foundation.businessType);
		$('input[name="foundationName"]').val(foundation.foundationName);
		$('input[name="address"]').val(foundation.address);
		$('input[name="location"]').val(foundation.location);
		$('input[name="feature"]').val(foundation.feature);
		$('input[name="pyung"]').val(foundation.pyung);
		$('input[name="grossFloor"]').val(foundation.grossFloor);
		$('input[name="floor"]').val(foundation.floor);
		$('input[name="contractType"]').val(foundation.contractType);
		$('input[name="leasePeriod"]').val(foundation.leasePeriod);
		$('input[name="foundingTime"]').val(foundation.foundingTime);
		$('input[name="dealingCause"]').val(foundation.dealingCause);
		$('input[name="leaseDeposit"]').val(foundation.leaseDeposit);
		$('input[name="facilitiesInvestment"]').val(foundation.facilitiesInvestment);
		$('input[name="unionFee"]').val(foundation.unionFee);
		$('input[name="totalFee"]').val(foundation.totalFee);
		$('input[name="monthlyRentalFee"]').val(foundation.monthlyRentalFee);
		$('input[name="commision"]').val(foundation.commision);
		$('input[name="serviceCharge"]').val(foundation.serviceCharge);
		$('input[name="feeReferences"]').val(foundation.feeReferences);
		$('input[name="salesPerDay"]').val(foundation.salesPerDay);
		$('input[name="salesPerMonth"]').val(foundation.salesPerMonth);
		$('input[name="employeeNumber"]').val(foundation.employeeNumber);
		$('input[name="personnelExpenses"]').val(foundation.personnelExpenses);
		$('input[name="materialCost"]').val(foundation.materialCost);
		$('input[name="netProfitPerMonth"]').val(foundation.netProfitPerMonth);
		$('input[name="seatingCapacity"]').val(foundation.seatingCapacity);
		$('input[name="peakTime"]').val(foundation.peakTime);
		$('input[name="operatingHour"]').val(foundation.operatingHour);
		$('input[name="operatingMethod"]').val(foundation.operatingMethod);
		$('textarea[name="businessDistrictZoneHistory"]').val(foundation.businessDistrictZoneHistory);
		$('textarea[name="salesHistory"]').val(foundation.salesHistory);
		$('textarea[name="note"]').val(foundation.note);
	}
	
	/**
	 * 보고서 팝업을 개방한다.
	 */
	function showReport(foundationId)
	{
		var windowName = '_FOUNDATION_REPORT_POPUP';
		
		window.open('', windowName, "width=710, height=760, toolbar=no, menubar=no, scrollbar=yes, resizable=no");
		
		$('#foundationEditForm').attr('target', windowName);
		$('#foundationEditForm').attr('action', '{0}/foundation/report'.format(contextPath));
		$('#foundationEditForm').submit();
	}
	
	/**
	 * 주어진 매장 아이디에 대한 매장 정보를 요청한다.
	 */
	function getFoundation(foundationId)
	{
		$.ajax(
		{
			url : '{0}/foundation/get'.format(contextPath),
			type : 'post',
			cache : false,
			data : { foundationId : foundationId },
			dataType : 'json',
			success : getFoundationCallback
		});
	}
	
	/**
	 * 매장 정보 요청에 대한 콜백이 실행된다.
	 */
	function getFoundationCallback(data)
	{
		setFoundationToForm(data.foundation);
	}
	
	/**
	 * 매장 정보 저장을 요청한다.
	 */
	function saveFoundation(event)
	{
		$(this).unbind('click');
		$(this).attr('disabled', true);
		
		oEditors.getById["businessDistrictZoneHistory"].exec("UPDATE_CONTENTS_FIELD", []);
		oEditors.getById["salesHistory"].exec("UPDATE_CONTENTS_FIELD", []);
		oEditors.getById["note"].exec("UPDATE_CONTENTS_FIELD", []);
		
		$.ajax(
		{
			url : '{0}/foundation/save'.format(contextPath),
			type : 'post',
			cache : false,
			data : $('#foundationEditForm').serialize(),
			dataType : 'json',
			success : saveFoundationCallback
		});
	}
	
	/**
	 * 매장 정보 저장 요청에 대한 콜백이 실행된다.
	 */
	function saveFoundationCallback(data)
	{
		$('#saveButton').unbind('click').click(saveFoundation);
		$('#saveButton').attr('disabled', false);
		
		foundationTable.fnDraw();
	}
}(jQuery));